package com.drop.android.sdk.bridge;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;

import com.drop.android.sdk.DropBusiness;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;

public class DropCocosBridge implements DropCocosIAP {

    private static DropCocosBridge callbackApi;
    public static WeakReference<Activity> mainGameActivity;
    private Method evalString;
    private Method runOnGLThread;
    private static Handler handler = new Handler(Looper.getMainLooper());

    public static DropCocosBridge getInstance() {
        if (callbackApi == null) {
            callbackApi = new DropCocosBridge();
        }
        return callbackApi;
    }

    public void setMainGameActivity(Activity activity) {
        mainGameActivity = new WeakReference<>(activity);

    }

    @Override
    public void XSSdkCallback(String action, String jsonData) {
        if (mainGameActivity != null && mainGameActivity.get() != null) {

            initRunOnGLThread();
            initEvalString();

            handler.post(() -> {
                try {
                    runOnGLThread.invoke(mainGameActivity.get(), (Runnable) () -> {
                        try {
                            evalString.invoke(null, String.format("window.DStSdkCallback('%s','%s')", action, jsonData));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

    private void initEvalString() {
        if (evalString == null) {
            try {
                Class clzBridge = Class.forName("org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge", false, DropBusiness.context.getClassLoader());
                evalString = clzBridge.getDeclaredMethod("evalString", String.class);
                evalString.setAccessible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void initRunOnGLThread() {
        if (runOnGLThread == null) {
            try {
                Class clzCocos2dAct = Class.forName("org.cocos2dx.lib.Cocos2dxActivity", false, DropBusiness.context.getClassLoader());
                runOnGLThread = clzCocos2dAct.getDeclaredMethod("runOnGLThread", Runnable.class);
                runOnGLThread.setAccessible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
